package com.jucai.pppeiyouclient.base;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.view.View;
import com.baidu.mapapi.SDKInitializer;
import com.fm.openinstall.OpenInstall;
import com.jucai.pppeiyouclient.bean.CityBean;
import com.jucai.pppeiyouclient.utils.CrashHandler;
import com.jucai.pppeiyouclient.utils.FileUtils;
import com.jucai.pppeiyouclient.utils.LocationHelper;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.ToastUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.ShareSDK;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import static com.jucai.pppeiyouclient.comm.CommonData.STORAGE_CACHE;
import static com.jucai.pppeiyouclient.comm.CommonData.STORAGE_PHOTO;
import static com.jucai.pppeiyouclient.comm.CommonData.STORAGE_PHOTO_CHAT;
import static com.jucai.pppeiyouclient.comm.CommonData.STORAGE_PHOTO_UPLOAD;
import static com.jucai.pppeiyouclient.comm.CommonData.STORAGE_PICTURE;
import static com.jucai.pppeiyouclient.comm.CommonData.STORAGE_PICTURE_DOWN;
import static com.jucai.pppeiyouclient.comm.CommonData.STORAGE_PICTURE_HEAD;

/**
 * Created by Kuky on 2017-02-23.
 */


public class BaseApplication extends MultiDexApplication {
    private static Context context;
    private String registrationId;
    private static BaseApplication baseApplication;
    public static String member_extension_id = "";


    public double mLatitude = 0;//22.799344
    public double mLongitude = 0;//108.360942
    public String mCity = null;//南宁
    public static List<CityBean> cityList;

    /**
     * 该字段只在会话列表里使用
     */
    public static String targetMemberId;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        baseApplication = this;
        createFile();

        /**
         * 百度地图
         */
        SDKInitializer.initialize(this);

        /**
         * 极光推送
         */
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
//        registrationId = JPushInterface.getRegistrationID(this);
//        SharedPreferencesUtil.saveStringPreference(getContext(), "j_push", "registration_id", registrationId);
//        LogUtils.e("BaseApplication ---> registration = " + registrationId);


        /**
         *
         * OnCreate 会被多个进程重入，这段保护代码，确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称，不可修改。
         */
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {

            /**
             * IMKit SDK调用第一步 初始化
             */
            RongIM.init(this);


            /**
             * 融云
             */
            RongIM.init(this);
            RongIM.setOnReceiveMessageListener(new MyReceiveMessageListener());
            RongIM.setConversationBehaviorListener(new MyConversationBehaviorListener());
            RongIM.setConversationListBehaviorListener(new MyConversationListBehaviorListener());

            connectRongIM();

        }

        /**
         * openInStall
         */
        OpenInstall.init(this);

        OpenInstall.setDebug(false);

        /**
         * OneKeyShare
         * */
        ShareSDK.initSDK(this);

        LocationHelper.init(this);
        // 全局异常捕获
//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(getApplicationContext());
    }

    private void connectRongIM() {
        String rongyun_token = LoginUtils.getRongyun_token(this);
        if (rongyun_token.equals("") || rongyun_token == null) {
            LogUtils.e("融云token为空");
            return;
        }
        LogUtils.e("融云connect开始...");
        RongIM.connect(rongyun_token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                LogUtils.e("onTokenIncorrect");
            }

            @Override
            public void onSuccess(String userId) {
                LogUtils.e("onSuccess:" + userId);
                LoginUtils.saveRongyun_id(BaseApplication.this, userId);

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                LogUtils.e("onError:" + errorCode.getMessage());
            }
        });
    }

    public void setJPushAliasAndTag() {
        if (!TextUtils.isEmpty(LoginUtils.getMember_id(this))) {
            Set<String> stringSet = new HashSet<>();
            stringSet.add("Android");
            stringSet.add("Client");

            JPushInterface.setAliasAndTags(this, LoginUtils.getMember_id(this), stringSet,mAliasCallback);
        } else {
            JPushInterface.setAliasAndTags(this, "", null,mAliasCallback);
        }
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:

                    logs = "Set tag and alias success";
                    LogUtils.e(logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtils.e(logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    Map<String, Object> param = new HashMap<>();
                    param.put("alias", alias);
                    param.put("tags", tags);
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(1001, param), 1000 * 60);
                    break;
                case 6012:
                    if (JPushInterface.isPushStopped(getApplicationContext()))
                        JPushInterface.resumePush(getApplicationContext());
                    Map<String, Object> param1 = new HashMap<>();
                    param1.put("alias", alias);
                    param1.put("tags", tags);
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(1001, param1), 1000);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtils.e(logs);
            }
        }
    };

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1001:
                    LogUtils.e("Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    Map<String, Object> map = (Map<String, Object>) msg.obj;
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) map.get("alias"), (Set<String>) map.get("tags"), mAliasCallback);
                    break;
                default:
                    LogUtils.e("Unhandled msg - " + msg.what);
            }
        }
    };

    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {

                return appProcess.processName;
            }
        }
        return null;
    }

    private class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {

        @Override
        public boolean onReceived(Message message, int left) {
            LogUtils.e("MyReceiveMessageListener 接收消息监听");
            return false;
        }
    }

    private class MyConversationBehaviorListener implements RongIM.ConversationBehaviorListener {

        @Override
        public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
            LogUtils.e("onUserPortraitClick");
            return false;
        }

        @Override
        public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
            LogUtils.e("onUserPortraitLongClick");
            return false;
        }

        @Override
        public boolean onMessageClick(Context context, View view, Message message) {
            LogUtils.e("onMessageClick");
            return false;
        }

        @Override
        public boolean onMessageLongClick(Context context, View view, Message message) {
            LogUtils.e("onMessageLongClick");
            return false;
        }

        @Override
        public boolean onMessageLinkClick(Context context, String link) {
            LogUtils.e("onMessageLinkClick");
            return false;
        }
    }

    private class MyConversationListBehaviorListener implements RongIM.ConversationListBehaviorListener {
        public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String targetId) {
            LogUtils.e("onConversationPortraitClick");
            return false;
        }

        public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String targetId) {
            LogUtils.e("onConversationPortraitLongClick");
            return false;
        }

        @Override
        public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
            LogUtils.e("onConversationLongClick");
            return false;
        }

        @Override
        public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
            LogUtils.e("onConversationClick:" + uiConversation.getUIConversationTitle());
            String rongyun_id = uiConversation.getUIConversationTitle();
            LogUtils.e("onConversationClick:" + rongyun_id);
            SharedPreferencesUtil.saveStringPreference(context, "rongyun", "rongyun_nickname", rongyun_id);
            if (rongyun_id.equals("") || rongyun_id == null) {
                ToastUtils.showToast("服务器异常，请稍后再试");
            } else {
                if (RongIM.getInstance() != null)
                    RongIM.getInstance().startPrivateChat(context, rongyun_id, rongyun_id);
            }
            return true;
        }
    }

    //获取全局Context
    public static Context getContext() {
        return context;
    }

    public static BaseApplication getBaseApplication() {
        return baseApplication;
    }

    private void createFile() {

        FileUtils.createDownPath();

        FileUtils.createDirectory(STORAGE_CACHE);

        FileUtils.createDirectory(STORAGE_PHOTO);

        FileUtils.createDirectory(STORAGE_PHOTO_CHAT);

        FileUtils.createDirectory(STORAGE_PHOTO_UPLOAD);

        FileUtils.createDirectory(STORAGE_PICTURE);

        FileUtils.createDirectory(STORAGE_PICTURE_HEAD);

        FileUtils.createDirectory(STORAGE_PICTURE_DOWN);
    }

}
